package cn.wolfcode.springboot_producer.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {
    @Autowired
    private RocketMQTemplate template;
    //演示同步发送
    @RequestMapping("/sendMsg")
    public String sendMsg(String msg){
        SendResult sendResult = template.syncSend("01-springboot", msg);
        System.out.println(sendResult.getSendStatus());
        System.out.println(sendResult.getMsgId());
        return "消息发送成功";
    }
    //演示异步发送
    @RequestMapping("/asyncSendMsg")
    public String asyncSendMsg(String msg){
        template.asyncSend("01-springboot", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("消息发送失败");
            }
        });
        return "消息发送成功";
    }
    //演示一次性发送
    @RequestMapping("/sendOneWayMsg")
    public String sendOneWayMsg(String msg){
        template.sendOneWay("01-springboot",msg);
        return "消息发送成功";
    }
    //演示延迟发送
    @RequestMapping("/delay")
    public String delay(String msg){
        MessageBuilder<String> builder = MessageBuilder.withPayload(msg);
        Message<String> message = builder.build();
        SendResult sendResult = template.syncSend("01-springboot", message,3000,3);
        System.out.println(sendResult.getSendStatus());
        System.out.println(sendResult.getMsgId());
        return "消息发送成功";
    }
    //演示标签过滤
    @RequestMapping("/tag")
    public String tagFilter(String msg,String tag){
        SendResult sendResult = template.syncSend("01-springboot:"+tag, msg);
        System.out.println(sendResult.getSendStatus());
        System.out.println(sendResult.getMsgId());
        return "消息发送成功";
    }
    //演示属性过滤
    @RequestMapping("/filter")
    public String filter(String msg){
        Map map = new HashMap<>();
        map.put("age",18);
        map.put("weight",100);
        map.put(MessageConst.PROPERTY_KEYS,"123");
        template.convertAndSend("01-springboot",msg,map);
        return "消息发送成功";
    }

}
